package com.common.utils;
/**
* @Description: RC4加密算法，用于生成随即不重复的邀请码
* @author LGC
* @date 2018年7月12日
* @version V1.0
*/
public class RC4 {

	private static String toHexString(String s) {
		String str = "";
		for(int i = 0; i < s.length(); i++) {
			int ch = (int) s.charAt(i);
			String s4 = Integer.toHexString(ch & 0xff);
			if(s4.length() == 1) {
				s4 = '0' + s4;
			}
			str += s4;
		}
		return str;
	}
	
	private static String asString(byte[] buf) {
		StringBuffer strBuf = new StringBuffer(buf.length);
		for(int i = 0; i < buf.length; i++) {
			strBuf.append((char) buf[i]);
		}
		return strBuf.toString();
	}
	
	private static byte[] initKey(String aKey) {
		byte[] bKey = aKey.getBytes();
		byte[] state = new byte[256];
		
		for(int i = 0; i < 256; i++) {
			state[i] = (byte) i;
		}
		
		int index1 = 0;
		int index2 = 0;
		if(bKey == null || bKey.length == 0) {
			return null;
		}
		for(int i = 0; i < 256; i++) {
			index2 = ((bKey[index1] & 0xff) + (state[i] & 0xff) + index2) & 0xff;
			byte tmp = state[i];
			state[i] = state[index2];
			state[index2] = tmp;
			index1 = (index1 + 1) % bKey.length;
		}
		return state;
	}
	
	private static byte[] RC4Base(byte[] input, String mKey) {
		int x = 0;
		int y = 0;
		byte[] key = initKey(mKey);
		int xorIndex;
		byte[] result = new byte[input.length];
		
		for(int i = 0; i < input.length; i++) {
			x = (x + 1) & 0xff;
			y = ((key[x] & 0xff) + y) & 0xff;
			byte tmp = key[x];
			key[x] = key[y];
			key[y] = tmp;
			xorIndex = ((key[x] & 0xff) + (key[y] & 0xff)) & 0xff;
			result[i] = (byte) (input[i] ^ key[xorIndex]);
		}
		return result;
	}
	
	public static byte[] encrypt_byte(String data, String key) {
		if(data == null || key == null) {
			return null;
		}
		byte bData[] = data.getBytes();
		return RC4Base(bData, key);
	}
	
	/**
	 * 加密
	 * 
	 * @param data 公钥
	 * @param key 密钥
	 * @return
	 */
	public static String encrypt(String data, String key) {
		if(data == null || key == null) {
			return null;
		}
		return toHexString(asString(encrypt_byte(data, key)));
	}
	
	
}
